﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Codemonk.Pease.Server.InterfaceActivators
{
    /// <summary>
    /// 基于约定的激活器
    /// 这个激活器会将命名空间中的Interfaces替换为Services,并将接口后面添加Implementation
    /// </summary>
    public class AppointActivator : IInterfaceActivator
    {
        private static IDictionary<string, Tuple<object, Type>> cache = new ConcurrentDictionary<string, Tuple<object, Type>>();

        public object CreateInstance(string interfaceName, out Type targetType)
        {
            Tuple<object, Type> value;
            if (cache.TryGetValue(interfaceName, out value))
            {
                targetType = value.Item2;
                return value.Item1;
            }
            else
            {
                var interfaceType = Type.GetType(interfaceName);
                var targetAssembly = interfaceType.Assembly.GetName().Name.Replace("Interfaces", "Services");
                var targetClass = string.Concat(interfaceType.Namespace.Replace("Interfaces", "Services"), ".", interfaceType.Name, "Implementation");
                targetType = Type.GetType(string.Concat(targetClass, ",", targetAssembly));
                var instance = Activator.CreateInstance(targetType);
                cache[interfaceName] = new Tuple<object, Type>(instance, targetType);
                return instance;
            }
        }
    }
}
